package com.yuexin.project.statistic.book.controller;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.google.common.collect.Lists;
import com.yuexin.project.mobile.Result;
import com.yuexin.project.mobile.ResultCode;
import com.yuexin.project.order.domain.MealsSetting;
import com.yuexin.project.order.service.ISettingService;
import com.yuexin.project.statistic.book.domain.EatBookList;
import com.yuexin.project.statistic.book.domain.StatsBook;
import com.yuexin.project.statistic.book.formbean.EatBookFormBean;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuexin.common.utils.poi.ExcelUtil;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.aspectj.lang.annotation.Log;
import com.yuexin.framework.aspectj.lang.enums.BusinessType;
import com.yuexin.framework.web.controller.BaseController;
import com.yuexin.framework.web.domain.AjaxResult;
import com.yuexin.framework.web.page.TableDataInfo;
import com.yuexin.project.statistic.book.domain.Book;
import com.yuexin.project.statistic.book.mapper.BookMapper;
import com.yuexin.project.statistic.book.service.IBookService;

/**
 * 报餐明细 信息操作处理
 *
 * @author yuexin
 * @date 2018-10-14
 */
@Controller
@RequestMapping("/statistic/book")
public class BookController extends BaseController {
    private String prefix = "statistic/book";
    @Autowired
    private IBookService bookService;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private ISettingService settingService;

    @RequiresPermissions("statistic:book:view")
    @GetMapping()
    public String book() {
        return prefix + "/book";
    }

    /**
     * 查询报餐明细列表
     */
    @RequiresPermissions("statistic:book:book")
    @PostMapping("/book")
    @ResponseBody
    public TableDataInfo list(Book book) {
        startPage();
        book.setCompanyId(ShiroUtils.getCompanyId());
        List<StatsBook> list = bookService.selectList(book);
        return getDataTable(list);
    }

    @GetMapping("/eatBooks")
    @ApiOperation("当前就餐数据")
    @ResponseBody
    public AjaxResult selectEatBook() {
        int h, mi;
        Calendar cal = Calendar.getInstance();
        h = cal.get(Calendar.HOUR_OF_DAY);
        mi = cal.get(Calendar.MINUTE);
        String companyId = ShiroUtils.getCompanyId();
        String dinnerType = getDinnerType(companyId, h + ":" + mi);
        if (!"0".equals(dinnerType) && !"1".equals(dinnerType) && !"2".equals(dinnerType) && !"3".equals(dinnerType)) {
            return error(-1, "现在不是就餐时间哦！");
        }
        EatBookFormBean form = new EatBookFormBean();
        form.setCompanyId(companyId);
        form.setCookUserId(ShiroUtils.getUserId());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        form.setEatTime(format.format(new Date()) + "%");
//		form.setEatTime("2019-03-19%");
        return success(bookService.selectEatBook(form));
    }

    /**
     * 新增报餐明细
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存报餐明细
     */
    @RequiresPermissions("module:book:add")
    @Log(title = "报餐明细", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Book book) {
        return toAjax(bookService.insertBook(book));
    }

    /**
     * 修改报餐明细
     */
    @GetMapping("/edit/{bookId}")
    public String edit(@PathVariable("bookId") Integer bookId, ModelMap mmap) {
        Book book = bookService.selectBookById(bookId);
        mmap.put("book", book);
        return prefix + "/edit";
    }

    /**
     * 修改保存报餐明细
     */
    @RequiresPermissions("module:book:edit")
    @Log(title = "报餐明细", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Book book) {
        return toAjax(bookService.updateBook(book));
    }

    /**
     * 删除报餐明细
     */
    @RequiresPermissions("module:book:remove")
    @Log(title = "报餐明细", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(bookService.deleteBookByIds(ids));
    }


    /**
     * 导出
     */
    @Log(title = "列表", businessType = BusinessType.EXPORT)
    @RequiresPermissions("statistic:book:export")
    @PostMapping("/exportbooklist")
    @ResponseBody
    public AjaxResult export(Book book) {
        book.setCompanyId(ShiroUtils.getCompanyId());
        List<StatsBook> list = bookService.selecExportList(book);
        ExcelUtil<StatsBook> util = new ExcelUtil(StatsBook.class);
        return util.exportExcel(list, "报餐明细");
    }

    /**
     * 根据扫码时间判断餐别
     *
     * @param companyId
     * @param time
     * @return
     */
    private String getDinnerType(String companyId, String time) {
        String dinnerType = "";
        MealsSetting mealsSetting = settingService.selectSettingByCompanyId(companyId);
        if (mealsSetting == null) {
            mealsSetting = settingService.selectSettingByCompanyId("dingcan");
        }
        String breakfastStart = mealsSetting.getBreakfastStart();
        String breakfastEnd = mealsSetting.getBreakfastEnd();
        String lunchStart = mealsSetting.getLunchStart();
        String lunchEnd = mealsSetting.getLunchEnd();
        String dinnerStart = mealsSetting.getDinnerStart();
        String dinnerEnd = mealsSetting.getDinnerEnd();
        String otherEnd = mealsSetting.getOtherEnd();

        if (compareTime(breakfastStart, time, breakfastEnd)) {
            dinnerType = "0";
        } else if (compareTime(lunchStart, time, lunchEnd)) {
            dinnerType = "1";
        } else if (compareTime(dinnerStart, time, dinnerEnd)) {
            dinnerType = "2";
        } else if (compareTime(dinnerEnd, time, otherEnd)) {
            dinnerType = "3";
        }
        return dinnerType;
    }

    private boolean compareTime(String start, String now, String end) {
        boolean result = false;
        DateFormat df = new SimpleDateFormat("HH:mm");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd
        try {
            Date startDate = df.parse(start);//将字符串转换为date类型
            Date nowDate = df.parse(now);
            Date endDate = df.parse(end);
            if ((nowDate.getTime() >= startDate.getTime()) && (nowDate.getTime() <= endDate.getTime()))//比较时间大小
            {
                result = true;
            }
        } catch (ParseException e) {
            result = false;
        }
        return result;
    }
}
